import { ComponentType, lazy } from 'react';
import { createBrowserRouter, redirect } from 'react-router-dom';
import { getToken } from '@/utils/auth';
import LoadComponent from "@/layout/index"
import Layout from "@/layout/layout"

const Login = lazy(() => import('@/views/login/login.tsx'))
const Index = lazy(() => import('@/views/home.tsx'))
const Page404 = lazy(() => import('@/views/404.tsx'))
const Config = lazy(() => import('@/views/config'))
const Solution = lazy(() => import('@/views/solution'))
const SolutionDetails = lazy(() => import('@/views/solution/detail'))


export const staticArr: any = [

    {
        path: '/',
        loader: () => {
            if (!getToken()) {
                return redirect('/login')
            }
            return redirect('/index')
        }
    },
    {
        path: '/index',
        title: "主页",
        element: (
            <LoadComponent>
                <Layout>
                    <Index />
                </Layout>
            </LoadComponent>
        )
    },
    {
        path: '/login',
        title: '登录页',
        hideSlide: true,
        element: (
            <LoadComponent>
                <Login />
            </LoadComponent>
        )
    },
    {
        path: '/config',
        title: "配置页",
        element: (
            <LoadComponent>
                <Layout>
                    <Config />
                </Layout>
            </LoadComponent>
        )
    },
    {
        path: '/solution',
        title: "解决方案",
        element: (
            <LoadComponent>
                <Layout>
                    <Solution />
                </Layout>
            </LoadComponent>
        ),
        children: [
            {
                path: 'details',
                title: "解决方案详情页",
                element: (
                    <LoadComponent>
                        <SolutionDetails />
                    </LoadComponent>)
            }
        ]
    },
    {
        path: '*',
        title: "404未知页",
        hideSlide: true,
        element: (
            <LoadComponent>
                <Page404 />
            </LoadComponent>
        )
    }
]

const routeKeys = ['path', 'loader', 'element', 'children']


const filterRouteData = (arr: any[]) => {
    return arr.map((el: any) => {
        let obj: any = {}
        if (el.children) {
            obj.children = filterRouteData(el.children)
        }
        for (const key in el) {
            if (routeKeys.includes(key)) {
                obj[key] = el[key]
            }
        }
        return obj
    })
}


export const slideData = staticArr.filter((el: { hideSlide: boolean; }) => !el.hideSlide)
const routeData = filterRouteData(staticArr)
const routes = createBrowserRouter(routeData)


export default routes;